﻿CREATE PROCEDURE [Event].[RSVP]
	@EventID INT,
	@AccountID INT = NULL,
	@EmailAddress NVARCHAR(255) = NULL,
	@Response BIT = NULL
WITH EXECUTE AS OWNER
AS
SET NOCOUNT ON;

IF @AccountID IS NULL AND @EmailAddress IS NULL
BEGIN
  RAISERROR('Either AccountID or EmailAddress must be supplied', 15, 0);
  RETURN;
END

DECLARE @sql AS NVARCHAR(MAX);
DECLARE @newline AS NVARCHAR(2);

SET @newline = NCHAR(13) + NCHAR(10);
SET @sql  = ' /* Event.RSVP */ 
UPDATE Event.Attendees
   SET Response = @response
 WHERE 1 = 1 ' + @newline;

IF @EmailAddress IS NOT NULL
  SET @sql += '   AND EmailAddress = @email_address ' + @newline;

IF @AccountID IS NOT NULL
  SET @sql += '   AND AccountID = @account_id ' + @newline;

BEGIN TRY
  BEGIN TRANSACTION
  
  EXEC sp_executesql @sql,
       N'@email_address NVARCHAR(255), @account_id INT, @response BIT',
       @EmailAddress, @AccountID, @Response;
  
  COMMIT TRANSACTION
END TRY
BEGIN CATCH
  IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
  
  DECLARE @ERROR_SEVERITY AS INT,
          @ERROR_STATE AS INT,
          @ERROR_NUMBER AS INT,
          @ERROR_LINE AS INT,
          @ERROR_MESSAGE AS NVARCHAR(4000);

  SELECT @ERROR_SEVERITY = ERROR_SEVERITY(),
         @ERROR_STATE = ERROR_STATE(),
         @ERROR_NUMBER = ERROR_NUMBER(),
         @ERROR_LINE = ERROR_LINE(),
         @ERROR_MESSAGE = ERROR_MESSAGE();

  RAISERROR('Msg %d, Line %d, :%s',
            @ERROR_SEVERITY,
            @ERROR_STATE,
            @ERROR_NUMBER,
            @ERROR_LINE,
            @ERROR_MESSAGE);
END CATCH